import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { ElMessage } from 'element-plus';

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/log/login.vue"),
  },
  {
    path: "/forgot",
    name: "Forgot",
    component: () => import("@/views/log/forgot.vue"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/log/register.vue"),
  },
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/welcome",
    name: "Welcome",
    component: () => import("@/views/profile/first-log.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/forumhome",
    name: "ForumHome",
    component: () => import("@/views/forum/forum-home.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/forum/:id",
    name: "ForumDetail",
    component: () => import("@/views/forum/forum-detail.vue"),
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: "/forum-create",
    name: "ForumCreate",
    component: () => import("@/views/forum/forum-create.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/forum-edit/:id",
    name: "ForumEdit",
    component: () => import("@/views/forum/forum-edit.vue"),
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: "/profile",
    name: "Profile",
    component: () => import("@/views/profile/personal.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/message",
    name: "Message",
    component: () => import("@/views/message/message-center.vue"),
    meta: { requiresAuth: true },
    children: [
      {
        path: "comment-like",
        name: "CommentLike",
        component: () => import("@/views/message/comment-like.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "system",
        name: "SystemMessage",
        component: () => import("@/views/message/system-message.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "",
        redirect: { name: "CommentLike" },
      },
    ],
  },
  {
    path: "/admin",
    component: () => import("@/views/admin/AdminLayout.vue"),
    children: [
      {
        path: "dashboard",
        name: "AdminDashboard",
        component: () => import("@/views/admin/AdminDashboard.vue"),
        meta: { requiresAdmin: true }
      },
      {
        path: "users",
        name: "UserManagement",
        component: () => import("@/views/admin/UserManagement.vue"),
        meta: { requiresAdmin: true }
      },
      {
        path: "posts",
        name: "PostManagement",
        component: () => import("@/views/admin/PostManagement.vue"),
        meta: { requiresAdmin: true }
      },
      {
        path: "resources",
        name: "ResourceManagement",
        component: () => import("@/views/admin/ResourceManagement.vue"),
        meta: { requiresAdmin: true }
      },
      {
        path: "reports",
        name: "ReportManagement",
        component: () => import("@/views/admin/ReportManagement.vue"),
        meta: { requiresAdmin: true }
      },
      {
        path: "login",
        name: "AdminLogin",
        component: () => import("@/views/admin/AdminLogin.vue"),
      },
    ],
  },
  {
    path: "/resources",
    name: "Resources",
    component: () => import("@/views/resources/resources.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/profile/:userId",
    name: "UserProfile",
    component: () => import("@/views/profile/user-profile.vue"),
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: "/create-center",
    component: () => import("@/views/create-center/center-home.vue"),
    meta: { requiresAuth: true },
    children: [
      {
        path: "forum-manager",
        name: "ForumManager",
        component: () => import("@/views/forum/forum-manager.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "resources-manager",
        name: "ResourcesManager",
        component: () => import("@/views/resources/resources-manager.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "",
        redirect: { name: "ForumManager" },
      },
    ],
  },
  {
    path: "/search",
    name: "SearchResult",
    component: () => import("@/views/search-result.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/ai-assistant",
    name: "AIAssistant",
    component: () => import("@/views/ai/AI-assistant.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/schedule",
    name: "Schedule",
    component: () => import("@/views/schedule/schedule.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/log/school-log",
    name: "SchoolLog",
    component: () => import("@/views/log/school-log.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/log/school-log/auto",
    name: "SchoolLogAuto",
    component: () => import("@/views/log/auto-school-log.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/favorites",
    name: "Favorites",
    component: () => import("@/views/favorites/favorites.vue"),
    meta: { requiresAuth: true }
  },
  {
    path: "/follow",
    name: "Follow",
    component: () => import("@/views/profile/follow.vue"),
  },
  // 404 路由，必须放在最后
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫 - 检查用户登录状态和管理员权限
router.beforeEach((to, from, next) => {
  // 检查路由是否需要管理员权限
  if (to.meta.requiresAdmin) {
    // 如果是从管理员登录页来的，不显示重复提示
    const fromAdminLogin = from.path === '/admin/login'
    
    // 检查管理员认证状态
    const adminInfo = getAdminFromLocalStorage()
    if (!adminInfo || !adminInfo.token) {
      if (!fromAdminLogin) {
        ElMessage.warning('请先使用管理员账号登录')
      }
      next('/admin/login')
      return
    }
    
    // 检查是否为管理员角色
    if (adminInfo.role !== 1) {
      if (!fromAdminLogin) {
        ElMessage.warning('权限不足，需要管理员权限')
      }
      next('/admin/login')
      return
    }
    
    // 检查token是否过期
    const expire = localStorage.getItem('adminExpire')
    if (expire && Date.now() > Number(expire)) {
      localStorage.removeItem('adminInfo')
      localStorage.removeItem('adminExpire')
      if (!fromAdminLogin) {
        ElMessage.warning('登录已过期，请重新登录')
      }
      next('/admin/login')
      return
    }
  }
  
  // 检查路由是否需要用户认证
  if (to.meta.requiresAuth) {
    // 检查是否有token
    const token = getTokenFromLocalStorage()
    if (!token) {
      // 没有token，显示提示信息并跳转到登录页
      ElMessage.warning('请先登录后再访问该页面')
      next('/login')
      return
    }
  }
  next()
})

// 从localStorage获取token的辅助函数
function getTokenFromLocalStorage() {
  try {
    const userInfo = localStorage.getItem('user')
    if (userInfo) {
      const user = JSON.parse(userInfo)
      return user.token || ''
    }
  } catch (e) {
    console.warn('获取token失败:', e)
  }
  return ''
}

// 从localStorage获取管理员信息的辅助函数
function getAdminFromLocalStorage() {
  try {
    const adminInfo = localStorage.getItem('adminInfo')
    if (adminInfo) {
      return JSON.parse(adminInfo)
    }
  } catch (e) {
    console.warn('获取管理员信息失败:', e)
  }
  return null
}

export default router;
